<?php 
session_start();
//ob_flush();
//if($REQUEST_METHOD=='POST'){
//	header('Expires: ' . gmdate("D, d M Y H:i:s", time()+1000) . ' GMT');
//	header('Cache-Control: public,must-revalidate');header("Pragma: no-cache");
//}

//$rootPath = $DOCUMENT_ROOT ."/";
require_once("config.php");
require_once("xtpl.php");


function record($sql,$pos,$field){

	if(($sql)&&($field)){

		$rs = mysql_query($sql) or die("<a href='/'>ERROR</a>");		

		if(mysql_num_rows($rs)>0){

			$record = mysql_result($rs,$pos,$field);

			return $record;

		}

		return "";

	}

}//endfunction



//set focus to combo box

function setfocus($cbovalue,$selected_key){

	return str_replace("'".$selected_key."'","'".$selected_key."' selected",$cbovalue);

}

//strip all html tag

	function strip_html($str){

		return str_replace(">","&gt;",str_replace("<","&lt;",$str));

	}

	function strip_quote($str){

		return str_replace("'","''",$str);

	}
	function formatData($str){
		$str = str_replace('"', '', $str);
		$str = str_replace("'", "", $str);
		$str = str_replace("\\", "", $str);
		return trim($str);		
	}

	function strip_quotes($str){

		$str = stripslashes($str);

		return str_replace("\"","&quot;",str_replace("'","&#39;",$str));

	

	}

	function strip_special($str){

		return eregi_replace("([\./~@?=%&! ]+)","",$str);		

	}





	function upload_file($path,$srcfile,$file_name="",$oldfile=""){				

		$time = date("YmdHis");

		if($srcfile!="none"){			

			//delete old file

			if($oldfile){

				$del_oldfile = $path.$oldfile;

				$deleted = deletefile ($del_oldfile);

			}//endif

			

			//add a new file

			$file_ext = substr($file_name,strrpos($file_name,".")+1);

			if((strtoupper($file_ext)=="PHP")||(strtoupper($file_ext)=="HTML")||(strtoupper($file_ext)=="HTM")){

				$file_name = $file_name.".css";

			}

			$file_name = $time."_".$file_name;

			$err=upload($srcfile,$path,$file_name);			

			if ($err!="") {				

				die($err); 		

			}else { 

			//upload OK --> return file info

				$uploaded_file = $file_name;	

			}//endif



		}else{

			$uploaded_file = $oldfile;

		}//endif

		return $uploaded_file;



	}//end function

//BEGIN: Luan
function deletefile($file_path){
	if (file_exists($file_path)) { 
		$deleted = unlink($file_path);
	}
	return $deleted;
}//end function deletefile

function upload_to_server($path,$srcfile,$file_name="",$oldfile=""){
	//global $rootPath;
	$unique = time();
	if($srcfile!="none"){		
		if($oldfile){
			$del_oldfile = $path.$oldfile;
			$deleted = deletefile($del_oldfile);
		}//endif	
		//add a new file
		$file_ext = substr($file_name,strrpos($file_name,".")+1);		if((strtoupper($file_ext)=="PHP")||(strtoupper($file_ext)=="HTML")||(strtoupper($file_ext)=="HTM")){
			$file_name = $file_name.".css";
		}
		$des_file = $unique."_".str_replace(" ","_",$file_name);
		$des_path = $rootPath.$path.$des_file;

		copy("$srcfile", $des_path) or 	die("Couldn't copy file.");
		$uploaded_file = $des_file;
	}else{
		$uploaded_file = $oldfile;	
	}
	return $uploaded_file;
}
function uploadfile($path,$new_file,$allow_type,$max_size)
{
	/*****************************************************************************/
	//$allow_type can be:
	//	0: Images only
	//	1: Images and doc, xls, mpp, vso, pdf, zip, rar file
	//	2: All
	//$path: path to store new file
	//$new_file: Posted value of file going to be uploaded.
	//$old_file_name: Name of the old file going to be replaced. Leave "" or name.
	//It will return
	//	Name of the uploaded file
	//	0: Invalid file type
	//	1: Exceed size
	// -1: Unable to upload file
	//	2: Not a file
	/*****************************************************************************/
	$filetmpname=$new_file['tmp_name'];
	if(is_file($filetmpname))
	{
		$filetype=$new_file['type'];
		$filesize=$new_file['size'];
		$filename=$new_file['name'];
		//Check max size
		if($filesize>$max_size)
		{
			return 1;
		}
		else if ($allow_type==0 && $filetype!="image/jpeg" && $filetype!='image/jpg' && $filetype!='image/gif' && $filetype!='image/png' && $filetype!="image/pjpeg" && $filetype!="image/bmp" && $filetype!="application/x-shockwave-flash")
		{
			return 0;
		}
		else if ($allow_type==1 && $filetype!="" && $filetype!="image/jpeg" && $filetype!='image/jpg' && $filetype!='image/gif' && $filetype!='image/png'  && $filetype!="image/pjpeg" && $filetype!="image/bmp" && $filetype!="application/x-shockwave-flash" && $filetype!="application/msword" && $filetype!="text/plain" && $filetype!="application/vnd.ms-excel" && $filetype!="application/pdf" && $filetype!="application/vnd.ms-project" && $filetype!="application/vnd.visio")
		{
			return 0;
		}
		else
		{
			//Upload file
			$unique=time();
			$filename=str_replace(" ","_",$filename);
			$new_name=$unique."_".$filename;
			$uploaded_file_full_path=$path.$new_name;
			if(move_uploaded_file($filetmpname,$uploaded_file_full_path))
			{
				return $new_name;
			}
			else
			{
				return -1;
			}
		}
	}
	else
	{
		return 2;
	}
}
function pagenavigator($page, $row_total, $page_size, $pagegroup_size,$class,$url) 

{

	// (strrpos ($url, "?")=== false) --> not found "?", so there aren't any conditions

	$andpage=(strrpos ($url,"?")===false)?"?page=":"&page=";



	$page_total = floor(($row_total-1)/$page_size)+1;

	

	if(!$page || $page > $page_total || $page < 1)

		$page = 1;



	$group = floor(($page-1)/$pagegroup_size)+1;

	$start_page = (($group-1)*$pagegroup_size)+1;

	$end_page = $start_page+$pagegroup_size-1;

	if ($end_page>$page_total) 

		$end_page = $page_total;



	if ($page_total>1) {

		$str='<table><tr height=5><td align=right class='.$class.'>';

		if ($end_page>$pagegroup_size)

			$start_group = $pagegroup_size;

		else

			$start_group = 0;

		if ($group>1)

			$str.= '<a style="text-decoration: none;" href="'.$url.$andpage.($start_page-$pagegroup_size).'">[10 Trang truoc]</a>';

		$str.="</td><td align=right class=$class>";

		$str.='</td><td align="center" valign="center" class='.$class.'>';

		for ( $i=$start_page ; $i <= $end_page ;$i++)

		{

			if ($i == $page)

				$str.= " $i ";

			else

				$str.= ' <a style="text-decoration: none;" href="'.$url.$andpage.$i.'"> '.$i.'</a> ';

		}

		$str.='</td><td  class=b>';

		$str.="</td><td class=".$class.">";		

		if ($page_total-$end_page>$pagegroup_size)

			$end_group = $pagegroup_size;

		else

			$end_group = $page_total-$end_page;

		if ($end_page<$page_total)

			$str.= '<a style="text-decoration: none;" href="'.$url.$andpage.($end_page+1).'">[10 Trang tiep]</a>';

		$str.='</td><td width=1></td></tr></table>';

		return $str;

	}	

}//end function pagenavigator
///
function thumbnail_images($image,$needed_width,$needed_height,$save_path,$needed_quality,$new_name_prefix,$updated_image) 
 {
	$img_name 		= $image['name'];
	$extension	=	pathinfo($img_name);  // Get File Extenstion
	if($extension['extension'] == "jpg" || $extension['extension'] == "pjpeg" || $extension['extension'] == "jpeg" || $extension['extension'] == "gif")
	{
		$img_tmp_name 	= $image['tmp_name'];
		$img_name_original 		= $image['name'];
		$img_name		=	$updated_image;
		if ("image/jpeg" !== $image['type'] &&
				"image/pjpeg" !== $image['type']&&
				"image/jpg" !== $image['type'] &&
				"image/gif" !== $image['type'] )	{
				return true;
		}
		$result = move_uploaded_file($img_tmp_name, $save_path.$img_name);
		if($image['type'] === "image/jpg" || 
				$image['type'] === "image/pjpeg" ||
				$image['type'] === "image/jpeg") {
				$src_img    = imagecreatefromjpeg($save_path.$img_name);
		}
		else if($image['type'] === "image/gif") {
				$src_img    = imagecreatefromgif($save_path.$img_name);
		}
		$size       = getimagesize($save_path.$img_name);
		list($src_width, $src_height) = $size;
		if ($src_width > $src_height) 
		{
		    $dest_width     = $needed_width;
		    $factor         = $needed_width / $src_width;
		    $dest_height    = $factor * $src_height;
		} 
		else 
		{
		    $dest_height    = $needed_height;
		    $factor         = $needed_height / $src_height;
		    $dest_width     = $factor * $src_width;
		}
		$dest_img = imagecreatetruecolor($dest_width, $dest_height);
		@imagecopyresampled($dest_img, $src_img, 0, 0, 0, 0, $dest_width, $dest_height, $src_width, $src_height);
		$thumb_name = $new_name_prefix."_" . $img_name;
		@imagejpeg($dest_img, $save_path.$thumb_name, 100);
		imagedestroy($src_img);
		imagedestroy($dest_img);
		return	$thumb_name;		
	}
	else
	{
		return ;
	}
}
///
function _POST($value){
	global $_GET, $_POST, $HTTP_POST_VARS,$HTTP_GET_VARS;
	if (isset($_POST["$value"]))
		return $_POST["$value"];
	elseif (isset($HTTP_POST_VARS["$value"]))
	    return $HTTP_POST_VARS["$value"];
	elseif (isset($_GET["$value"]))
	    return $_GET["$value"];
	elseif (isset($HTTP_GET_VARS["$value"]))
	    return $HTTP_GET_VARS["$value"];
	else
	    return ;
}
function READ_SESSION($session_name)
{
    return $_SESSION[$session_name];
}
function WRITE_SESSION($session_name, $session_value)
{
	$_SESSION[$session_name]=$session_value;
}
function formatDataForMySql($data)
{
	$data=str_replace("\\",'',$data);
	$data=str_replace('"',"&quot;",$data);
	$data=str_replace("'","&#039;",$data);
	return $data;
}
function codau2kodau( $str){
	$str = preg_replace("/(à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ)/",  'a', $str);
	$str = preg_replace ("/(è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)/", 'e', $str );
	$str = preg_replace("/(ì|í|ị|ỉ|ĩ)/" , 'i', $str);
	$str  = preg_replace("/(ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ)/", 'o' , $str);
	$str = preg_replace ("/(ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)/", 'u', $str );
	$str = preg_replace("/(ỳ|ý|ỵ|ỷ|ỹ)/" , 'y', $str);
	$str =  preg_replace("/(đ)/", 'd', $str );

	$str = preg_replace("/(À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ)/" , 'A', $str);
	$str  = preg_replace("/(È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ)/", 'E' , $str);
	$str = preg_replace( "/(Ì|Í|Ị|Ỉ|Ĩ)/", 'I', $str);
	$str  = preg_replace("/(Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ)/",  'O', $str);
	$str = preg_replace ("/(Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ)/", 'U', $str );
	$str = preg_replace("/(Ỳ|Ý|Ỵ|Ỷ|Ỹ)/" , 'Y', $str);
	$str =  preg_replace("/(Đ)/", 'D', $str );
	$str = str_replace(" ", "-", str_replace("&*#39;","",$str));
	$str = str_replace("?", "", str_replace("&*#39;","",$str));
	$str = str_replace("!", "", str_replace("&*#39;","",$str));
	$str = str_replace(".", "-", str_replace("&*#39;","",$str));
	$str = str_replace(",", "", str_replace("&*#39;","",$str));
	$str = str_replace(":", "", str_replace("&*#39;","",$str));
	$str = str_replace("–", "", str_replace("&*#39;","",$str));
	return  htmlspecialchars($str);
}
function cfopen($url, $limit = 8192)
{
	$matches = parse_url($url);
	$host = $matches['host'];
	$script = (isset($matches['path'])?$matches['path']:'/').(isset($matches['query'])?'?'.$matches['query']:'').(isset($matches['fragment'])?'#'.$matches['fragment']:'');
	$port = !empty($matches['port']) ? $matches['port'] : 80;

	$out = "GET $script HTTP/1.1\r\n";
	$out .= "Accept: */*\r\n";
	$out .= "Accept-Language: en-us\r\n";
	$out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
	$out .= "Host: $host\r\n";
	$out .= "Connection: Close\r\n\r\n";

	$fp = fsockopen($host, $port, $errno, $errstr, 30);

	$return = '';
	if($fp)
	{
		stream_set_blocking($fp, TRUE);
		stream_set_timeout($fp, 30);
		@fwrite($fp, $out);
		$status = stream_get_meta_data($fp);
		if ( !$status['timed_out'] )
		{
			while(!feof($fp)) {
				$return .= @fread($fp, $limit);
			}
			$return = preg_replace("/\r\n\r\n/", "\n\n", $return, 1);
			$strpos = strpos($return, "\n\n");
			$strpos = $strpos !== FALSE ? $strpos + 2 : 0;
			$return = substr($return, $strpos);
		}
	}
	@fclose($fp);
	return $return;
}
?>